package com.cloudpivot.receivales.ding.robot.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import com.cloudpivot.receivales.ding.robot.service.DocSpaceServiceImpl;
import com.cloudpivot.receivales.ding.userinfo.service.DingUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

//启动后 启动
@Controller
@Slf4j
@RequestMapping("/dingrobot/mapping")
public class StartRunnerController implements CommandLineRunner {

    @Autowired
    private DocSpaceServiceImpl docSpaceService;

    @Autowired
    private DingUserService dingUserService;

    @Autowired
    private DingBasicService dingBasicService;

    @Value("${localtest.flag}")
    private String LOCALFLAG;

    @Override
    public void run(String... args) throws Exception {
        if (!Boolean.valueOf(LOCALFLAG)) {
            Map<String, String> _map = new HashMap<>();
            String unionId = dingUserService.dingUidToUnionId("020722623423157211");
            String access_token = dingBasicService.getToken("dinggroup");

            docSpaceService.getAllFileIteration(unionId, "", _map, access_token);
            docSpaceService.filemaps = _map;
            log.info("构建当前目录map成功");
        }
    }

    /**
     * 测试用 调用字典接口
     *
     * @return
     */
    @GetMapping("/getWorkspaceMapping")
    @ResponseBody
    public JSONObject getWorkspaceMapping() {

        return JSONObject.parseObject(JSONObject.toJSONString(docSpaceService.filemaps));
    }

    @GetMapping("/updateWorkspaceMapping")
    public String updateWorkspaceMapping() {
        //清空 字典
        docSpaceService.filemaps.clear();
        //重新装载 知识库字典
        Map<String, String> _map = new HashMap<>();
        String unionId = dingUserService.dingUidToUnionId("020722623423157211");
        String access_token = dingBasicService.getToken("dinggroup");

        docSpaceService.getAllFileIteration(unionId, "", _map, access_token);
        docSpaceService.filemaps = _map;
        log.info("重新装载知识库字典成功");
        return "重新装载知识库字典成功";
    }
}
